package com.xiao.androidcompose01.service

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat

class MediaService: Service() {
   private val NOTIFICATION_CHANNEL_ID="com.tencent.trtc.apiexample.MediaService";
   private val NOTIFICATION_CHANNEL_NAME="com.tencent.trtc.apiexample.channel_name";
   private val NOTIFICATION_CHANNEL_DESC="com.tencent.trtc.apiexample.channel_desc";
   
   override fun onCreate() {
      super.onCreate()
      startNotification()
   }
   fun startNotification() {
      //Call Start foreground with notification
      val notificationIntent = Intent(this, MediaService::class.java)
      val pendingIntent:PendingIntent
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
         pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
      } else {
         pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            PendingIntent.FLAG_IMMUTABLE)
      }
      val notificationBuilder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
         .setLargeIcon(BitmapFactory.decodeResource(getResources(), com.xiao.androidcompose01.R.drawable.ic_launcher_foreground))
         .setSmallIcon(com.xiao.androidcompose01.R.drawable.ic_launcher_foreground)
         .setContentTitle("Starting Service")
         .setContentText("Starting monitoring service")
         .setContentIntent(pendingIntent);
      val notification = notificationBuilder.build()
      val channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
      channel.description = NOTIFICATION_CHANNEL_DESC
      
      val notificationManager = ContextCompat.getSystemService(this, NotificationManager::class.java)
      notificationManager?.createNotificationChannel(channel);
      startForeground(1, notification); //必须使用此方法显示通知，不能使用notificationManager.notify，否则还是会报上面的错误
   }
   
   override fun onBind(intent: Intent?): IBinder? {
      throw UnsupportedOperationException("Not yet implemented")
   }
}